package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.dto.*;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApAuthor;
import com.heima.article.entity.ApCollection;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author wsj
 * @since 2022-03-11
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {
    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    @Lazy
    private IArticleStaticUrl articleStaticUrl;
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        //判断文章id是否存在，不存在则保存文章
        //存在则修改文章
        ApArticle apArticle=new ArticleDto();
        BeanUtils.copyProperties(dto,apArticle);
        saveOrUpdate(apArticle);
        //保存或修改文章内容
        ApArticleContent content=new ApArticleContent();
        content.setArticleId(apArticle.getId());
        content.setContent(dto.getContent());
        //如果是修改文章内容，构建修改条件
        LambdaUpdateWrapper<ApArticleContent> query=new LambdaUpdateWrapper<>();
        query.eq(ApArticleContent::getArticleId,apArticle.getId());
        query.set(ApArticleContent::getContent,dto.getContent());
        contentService.saveOrUpdate(content,query);
        //异步静态页面
        articleStaticUrl.createStaticUrl(apArticle,dto.getContent());
        //返回文章id
        return ResponseResult.okResult(apArticle.getId());
    }
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto,Integer type) {
        //显示热门文章
        if (dto.getLoaddir()==1) {
            List<ApArticle> list = new ArrayList<>();
            Set<String> strings = redisTemplate.opsForZSet().reverseRange("hotArticle_" + dto.getChannelId(), 0, dto.getSize() - 1);
            if (!CollectionUtils.isEmpty(strings)) {
                for (String string : strings) {
                    ApArticle apArticle = JSON.parseObject(string, ApArticle.class);
                    list.add(apArticle);
                }
                if (list.size()==dto.getSize()) {
                    return ResponseResult.okResult(list);
                }
            }
        }
        //构建查询条件
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
        //是否选择频道
        if (dto.getChannelId()!=null&&dto.getChannelId()!=0) {
            query.eq(ApArticle::getChannelId,dto.getChannelId());
        }
        //每页显示几条，默认10条
        if (dto.getSize()==null||dto.getSize()<=0||dto.getSize()>50) {
            dto.setSize(10);
        }
        //是否上拉，获取更多文章
        if (type==2) {
            query.le(ApArticle::getPublishTime,dto.getMinTime());
        }
        //是否下拉，获取最新
        if (type==3) {
            query.ge(ApArticle::getPublishTime,dto.getMinTime());
        }
        //按发布时间倒序
        query.orderByDesc(ApArticle::getPublishTime);
        //排除已删除和已下架的
        query.eq(ApArticle::getIsDelete,false);
        query.eq(ApArticle::getIsDown,false);
        //分页查询
        IPage<ApArticle> page=new Page<>(1,dto.getSize());
        IPage<ApArticle> iPage = page(page, query);
        //返回结果
        return ResponseResult.okResult(iPage.getRecords());
    }
    @Autowired
    private IApArticleContentService apArticleContentService;
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //根据文章id查询文章
        ApArticle apArticle = getById(dto.getArticleId());
        //文章不存在或者已被下架、删除，返回提示：数据不存在
        if (apArticle==null||apArticle.getIsDelete()||apArticle.getIsDown()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //文章正常，查询文章内容
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId,apArticle.getId());
        ApArticleContent content = apArticleContentService.getOne(wrapper);
        //返回前端需要的格式
        Map<String, Object> map = new HashMap<>();
        map.put("config",apArticle);
        map.put("content", content);
        //返回
        return ResponseResult.okResult(map);
    }
    @Autowired
    private BehaviorFeign behaviorFeign;
    @Autowired
    private IApAuthorService apAuthorService;
    @Autowired
    private IApCollectionService collectionService;
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //文章详情行为回显
        //获取当前文章用户id
        ApAuthor apAuthor = apAuthorService.getById(dto.getAuthorId());
        dto.setFollowUserId(apAuthor.getUserId());
        //获取当前线程中的user
        User user = AppThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        dto.setUserId(user.getId());
        //调用行为微服务
        ResponseResult<BehaviorVo> result = behaviorFeign.getBehavior(dto);
        BehaviorVo behaviorVo=null;
        if (result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            behaviorVo = result.getData();
        }
        //查询当前文章是否收藏
        LambdaQueryWrapper<ApCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApCollection::getEntryId,behaviorVo.getEntryId());
        wrapper.eq(ApCollection::getArticleId,dto.getArticleId());
        ApCollection apCollection = collectionService.getOne(wrapper);
        if (apCollection!=null) {
            behaviorVo.setIscollection(true);
        }
        return ResponseResult.okResult(behaviorVo);
    }

    @Override
    public ResponseResult loadArticleComments(ArticleCommentDto dto) {
        //查看文章列表
        //获取当前线程中的user
        User user = AppThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询作者
        LambdaQueryWrapper<ApAuthor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApAuthor::getWmUserId,user.getId());
        ApAuthor apAuthor = apAuthorService.getOne(wrapper);
        //构建分页
        IPage<ApArticle> page=new Page<>(dto.getPage(),dto.getSize());
        //查询条件
        LambdaQueryWrapper<ApArticle> query=new LambdaQueryWrapper<>();
        //当前登录用户文章
        query.eq(ApArticle::getAuthorId,apAuthor.getId());
        //发布时间倒叙
        query.orderByDesc(ApArticle::getPublishTime);
        //起始时间
        if (!StringUtils.isEmpty(dto.getBeginDate())) {
            query.ge(ApArticle::getPublishTime,dto.getBeginDate());
        }
        //结束时间
        if (!StringUtils.isEmpty(dto.getEndDate())) {
            query.le(ApArticle::getPublishTime, dto.getEndDate());
        }
        //分页查询
        IPage<ApArticle> iPage = page(page, query);
        //返回分页对象
        return new PageResponseResult(dto.getPage().longValue(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
    }

    @Override
    public ResponseResult updateCommentStatus(ArticleCommentStatusDto dto) {
        //打开或关闭评论
        ApArticle apArticle = new ArticleDto();
        apArticle.setId(dto.getArticleId());
        apArticle.setIsComment(dto.getOperation()==1?true:false);
        updateById(apArticle);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult newsDimension(String beginDate, String endDate) {
        //图文统计
        //构建查询条件
        //获取当前线程中的user
        User user = AppThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询当前作者id
        LambdaQueryWrapper<ApAuthor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApAuthor::getWmUserId, user.getId());
        ApAuthor author = apAuthorService.getOne(queryWrapper);
        LambdaQueryWrapper<ApArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(ApArticle::getPublishTime, beginDate);
        wrapper.le(ApArticle::getPublishTime, endDate);
        wrapper.eq(ApArticle::getAuthorId, author.getId());
        List<ApArticle> apArticles = list(wrapper);
        //封装vo
        NewDimensionVo vo = new NewDimensionVo();
        vo.setPublishNum(apArticles.size());
        int likeNum=0;
        int collectNum=0;
        if (!CollectionUtils.isEmpty(apArticles)) {
            for (ApArticle apArticle : apArticles) {
                likeNum += apArticle.getLikes();
                collectNum += apArticle.getCollection();
            }
        }
        vo.setCollectNum(collectNum);
        vo.setLikesNum(likeNum);
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult getNewsPageStatistics(String beginDate, String endDate, Integer page, Integer size) {
        //图文列表
        ArticleCommentDto dto = new ArticleCommentDto();
        dto.setBeginDate(beginDate);
        dto.setEndDate(endDate);
        dto.setPage(page);
        dto.setSize(size);
        return loadArticleComments(dto);
    }
}
